package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.TestItem;
import com.tianxin.workbao.workBao.bean.TestItemDao;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.helper.GreenDaoHelper;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.exception.OkHttpException;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.BeansUtil;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;
import com.tianxin.workbao.workBao.utils.common.UIUtils;

import org.greenrobot.greendao.query.Query;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hacker on 2017/7/17.
 */

public class TestItemProvide extends BaseDataProvide {
    private Integer mPage;
    private List<TestItem> mTestItems;
    private int isFromServer;
    private UpdateListViewListener mUpdateListViewListener;
    private Handler mSaveDbHandler;


    public TestItemProvide(Context context, UpdateListViewListener listener) {
        super(context);
        mUpdateListViewListener = listener;
        isFromServer = 0;
        mSaveDbHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                TestItemDao testItemDao = GreenDaoHelper.newInstance().getDaoSession().getTestItemDao();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(msg.obj.toString());
                    String resData = jsonObject.getString("data");
                    if (resData.startsWith("[") && resData.endsWith("]") && resData.length() > 3) {
                        mTestItems = BeansUtil.testItemToBeans(resData);
                        for (TestItem item : mTestItems) {
                            testItemDao.insertOrReplace(item);
                        }
                    } else {
                        TestItem item = BeansUtil.testItemToBean(resData);
                        mTestItems.add(item);
                        testItemDao.insertOrReplace(item);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                isFromServer = 1;
                getFromDb(1);
            }
        };
    }

    private void getFromDb(int page) {
        TestItemDao testItemDao = mGreenDaoHelper.getDaoSession().getTestItemDao();
        Query<TestItem> query = testItemDao.queryBuilder().where(TestItemDao.Properties.Isis.eq(1))
                .offset((page - 1) * Constant.COAL_PAGE_SIZE)
                .limit(Constant.COAL_PAGE_SIZE)
                .build();
        mTestItems = query.list();
    }

    @Override
    public DisposeDataHandle getDisposeDataHandle() {
        disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        disposeDataListener = new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                mUpdateListViewListener.hideProgress();
                try {
                    JSONObject object = new JSONObject(responseObj.toString());
                    int status = object.getInt(Constant.RESPONSE_STATUS);
                    String information = object.getString(Constant.RESPONSE_INFO);
                    if (status > 0) {
                        String dataJson = object.getString(Constant.RESPONSE_DATA);
                        if (dataJson != null || dataJson.length() > 2) {
                            try {
                                if (dataJson.startsWith("[") && dataJson.endsWith("]") && dataJson.length() > 3) {
                                    mTestItems = BeansUtil.testItemToBeans(dataJson);
                                    refreshUI();
                                    saveToDb(mTestItems);
                                } else {
                                    TestItem item = BeansUtil.testItemToBean(dataJson);
                                    mTestItems.clear();
                                    mTestItems.add(item);
                                    refreshUI();
                                    saveToDb(mTestItems);
                                }
                            } catch (Exception e) {
                                mUpdateListViewListener.showMessage("test item To Bean Error :类型转换出错");
                            }

                        } else {
                            mUpdateListViewListener.showMessage(information);
                        }
                    } else {
                        mUpdateListViewListener.showMessage(information);
                    }

                } catch (JSONException e) {
                    showRequestErrorMessage(mUpdateListViewListener,responseObj.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                mUpdateListViewListener.hideProgress();
                if (reasonObj instanceof OkHttpException) {
                    OkHttpException exception = (OkHttpException) reasonObj;
                    mUpdateListViewListener.showMessage(exception.getEcode() + ":" + exception.getEmsg().toString());
                } else {
                    showRequestErrorMessage(mUpdateListViewListener,reasonObj.toString());
                }
            }
        };
        return disposeDataListener;
    }

    /**
     * true save data to databases
     *
     * @param obj
     */
    private void saveToDb(Object obj) {
        TestItemDao testItemDao = mGreenDaoHelper.getDaoSession().getTestItemDao();
        if (obj instanceof List) {
            for (int i = 0; i < mTestItems.size(); i++) {
                testItemDao.insertOrReplace(mTestItems.get(i));
            }
        } else {
            testItemDao.insertOrReplace((TestItem) obj);
        }
    }

    /**
     * get coals 获取化验项列表
     *
     * @param page
     */
    public void getTestItems(int page) {
        mPage = page;
        getFromDb(page);
        if (mTestItems == null || mTestItems.isEmpty()) {
            if (isFromServer == 0) {
                updateFromServer();
                getTestItems(page);
            } else {
                mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.no_data));
            }
        }
        refreshUI();
    }

    /**
     * update the Test item data  from server
     */
    private void updateFromServer() {
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
        } else {
            mUpdateListViewListener.showProgress();
            isFromServer = 1;
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            RequestParams params = new RequestParams(map);
            CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getTestItemUrl(), params), getDisposeDataHandle());
        }
    }

    @Override
    public void refreshUI() {
        if (mTestItems != null && !mTestItems.isEmpty()) {
            if (mPage > 1) {
                mUpdateListViewListener.onLoadMoreData(mTestItems);
            } else {
                mUpdateListViewListener.onRefreshData(mTestItems);
            }
        }
    }
}
